import { defineStore } from 'pinia'
import $axios from "../plugins/http"
import { Base64 } from 'js-base64'

export const useDynamicPinia = defineStore('dynamic', {
  state: () => ({
    dynamicDatas: {
      // 是否为最后一页
      isLast: false,
      isRequest: false,
      isHasNew: false,
      value: new Map() as Map<string, Dynamic>,
      // 是否需要重新请求
      isReload: false,
    },
    mySelfDynamicDatas: {
      isLast: false,
      value: new Map() as Map<string, Dynamic>,
      isRequest: false,
      // 是否需要重新请求
      isReload: false,
    },
  }),
  actions: {
    // 使用默认封面
    async useDefaultCover(): Promise<number> {
      return await $axios(
        ['/dynamic/useDefaultCover', 'patch'],
        async () => {
          const { useUserPinia } = await import('@/pinia/user');
          useUserPinia().user.bkImg = '';
        }
      )
    },
    // 发送动态
    async sendDynamic(payload: {
      selfId: string;
      content: string;
      imgs: Array<string>;
      permission: {
        tagType: 0 | 1 | 2 | 3;
        childrenType: 0 | 1;
        children: Array<string>;
      },
    }): Promise<number> {
      const userId: string = payload.selfId;
      payload.selfId = Base64.encode(userId);
      return await $axios(
        ['/dynamic/send', 'post', payload],
        () => {
          if (this.dynamicDatas.isRequest && !this.dynamicDatas.isReload)
            this.dynamicDatas.isReload = true;
          if (this.mySelfDynamicDatas.isRequest && !this.mySelfDynamicDatas.isReload)
            this.mySelfDynamicDatas.isReload = true
        }
      )
    },
    // 请求动态数据
    async getDynamic(payload: {
      senderId: string;
      userId: string;
      lastDynamicId?: string;
      firstDynamicId?: string;
      isSelfDynamic?: boolean;
    }) {
      const otherId: string = payload.userId;
      const selfId: string = payload.senderId;
      payload.userId = Base64.encode(payload.userId);
      payload.senderId = Base64.encode(payload.senderId);
      return new Promise<{
        code: number;
        dynamicDatas: Map<string, Dynamic>;
        isLast: boolean;
      }>((resolve, reject) => {
        let dynamicDatas: Map<string, Dynamic> = new Map();
        // 该数据是否为最后一页
        let isLast: boolean = false;
        $axios(
          ['/dynamic/getDatas', 'post', payload],
          (data: {
            value: any;
            isLast: boolean;
          }) => {
            const mapDatas = new Map(data.value) as Map<string, any>;
            for (const value of mapDatas.values()) {
              value.thumbs = new Map(value.thumbs);
              value.comments = new Map(value.comments);
            }
            if (otherId === selfId)
              if (payload.isSelfDynamic) {
                if (payload.lastDynamicId)
                  for (const [key, value] of mapDatas.entries())
                    this.mySelfDynamicDatas.value.set(key, value)
                else {
                  const dataArr = [...this.mySelfDynamicDatas.value];
                  dataArr.unshift(...data.value);
                  this.mySelfDynamicDatas.value = new Map(dataArr);
                }
                this.mySelfDynamicDatas.isRequest = true;
                this.mySelfDynamicDatas.isReload = false;
                if (!payload.firstDynamicId) this.mySelfDynamicDatas.isLast = data.isLast;
                isLast = this.mySelfDynamicDatas.isLast;
              }
              else if (payload.lastDynamicId) {
                for (const [key, value] of mapDatas)
                  this.dynamicDatas.value.set(key, value);
                this.dynamicDatas.isLast = data.isLast;
                isLast = this.dynamicDatas.isLast;
              }
              else {
                const dataArr = [...this.dynamicDatas.value];
                dataArr.unshift(...data.value);
                this.dynamicDatas.value = new Map(dataArr);
                this.dynamicDatas.isHasNew = false;
                this.dynamicDatas.isRequest = true;
                this.dynamicDatas.isReload = false;
                if (!payload.firstDynamicId) this.dynamicDatas.isLast = data.isLast;
                isLast = this.dynamicDatas.isLast;
              }
            // 如果请求的是他人的动态
            else {
              for (const [key, value] of mapDatas)
                dynamicDatas.set(key, value);
              isLast = data.isLast;
            }
          },
        ).then(code => resolve({ code, dynamicDatas, isLast })).catch(() => reject())
      })
    },
    // 不显示某一动态或者是删除某一动态
    async opearDynamic(payload: {
      dynamicId: string;
      type: 0 | 1;
    }): Promise<number> {
      return await $axios(
        ['/dynamic/opearDynamic', 'delete', payload],
        () => {
          if (this.dynamicDatas.value.size && this.dynamicDatas.value.has(payload.dynamicId))
            this.dynamicDatas.value.delete(payload.dynamicId);
          this.mySelfDynamicDatas.value.size &&
            this.mySelfDynamicDatas.value.has(payload.dynamicId) &&
            this.mySelfDynamicDatas.value.delete(payload.dynamicId);
        },
      )
    },
    // 对动态进行点赞
    async thumbDynamic(payload: {
      dynamicId: string;
    }, info: {
      selfId: string;
      remark: string;
    }): Promise<number> {
      return await $axios(
        ['/dynamic/thumbDynamic', 'patch', payload],
        () => {
          const data = this.dynamicDatas.value.get(payload.dynamicId);
          const myData = this.mySelfDynamicDatas.value.get(payload.dynamicId);
          if (data && !data.thumbs.delete(info.selfId))
            data.thumbs.set(info.selfId, { remark: info.remark })
          if (myData && !myData.thumbs.delete(info.selfId))
            myData.thumbs.set(info.selfId, { remark: info.remark })
        }
      )
    },
    // 对动态进行评论或者回复评论
    commentDynamic(payload: {
      dynamicId: string;
      commentId?: string;
    }, info: DynamicCommenter & { commentContent: string }): Promise<{
      code: number;
      commentId: string;
    }> {
      let commentid: string = '';
      return new Promise<{ code: number; commentId: string }>((resolve, reject) => {
        $axios(
          ['/dynamic/commentDynamic', 'post', {
            dynamicId: payload.commentId ? undefined : payload.dynamicId,
            commentId: payload.commentId,
            commentContent: info.commentContent,
          }],
          ({ commentId }) => {
            commentid = commentId;
            const data = this.dynamicDatas.value.get(payload.dynamicId);
            const myData = this.mySelfDynamicDatas.value.get(payload.dynamicId);
            if (data) data.comments.set(commentId, info);
            if (myData) myData.comments.set(commentId, info);
          }
        ).then((code) => resolve({ code, commentId: commentid })).catch(() => reject())
      })
    },
    // 删除动态评论
    async commentDynamicDelete(payload: {
      dynamicId: string;
      commentId: string;
    }): Promise<number> {
      return await $axios(
        ['/dynamic/commentDynamicDelete', 'delete', {
          commentId: payload.commentId,
        }],
        () => {
          const data = this.dynamicDatas.value.get(payload.dynamicId);
          const myData = this.mySelfDynamicDatas.value.get(payload.dynamicId);
          if (data) data.comments.delete(payload.commentId);
          if (myData) myData.comments.delete(payload.commentId);
        }
      )
    },
  },
})